import React, { useState } from "react";
import { Typography, Button, Card, Space, Row, Col, Tabs, Collapse } from "antd";
import { EyeOutlined, FileTextOutlined } from "@ant-design/icons";
import markdownit from "markdown-it";
import { Answer } from "./types";
import { FlightOption, SimplifiedFlightInfo } from "../../services/apiService";
import { useTranslation } from 'react-i18next';
import i18n from "../../locales/i18n";

// 配置 markdown-it 以支持 HTML 和更好的渲染
const md = markdownit({
  html: true, // 允许 HTML 标签
  breaks: true, // 转换换行符
  linkify: true, // 自动转换链接
  typographer: true, // 启用一些语言中性的替换 + 引号美化
});

interface FlowContentRendererProps {
  answer: Answer;
  onFlowHtmlClick: (content: string) => void;
  onFlowProductIdClick?: (productId: string, flightInfo?: FlightOption, flightList?: FlightOption[],
    callback?: () => void
  ) => void;
  onSummaryClick?: (
    content: string,
    type: "html" | "product",
    metadata: { answerId: string; messageItemId: string }
  ) => void;
  onSummaryResultClick?: (summaryContent: string) => void;
  onSaveMultilang?: (summaryContent: string, originalContent: string, productId?: string) => void; // 新增保存多语言回调
}

const FlowContentRenderer: React.FC<FlowContentRendererProps> = ({
  answer,
  onFlowHtmlClick,
  onFlowProductIdClick,
  onSummaryClick,
  onSummaryResultClick,
  onSaveMultilang, // 新增
}) => {
  const { display, summaries, think, status } = answer;
  const [activeSummaryId, setActiveSummaryId] = useState<string | null>(null);
  const { t } = useTranslation();

  // 提取 flow_html 内容的函数
  const extractFlowHtmlContent = (content: string): string | null => {
    const regex = /<flow_html>([\s\S]*?)<\/flow_html>/;
    const match = content.match(regex);
    return match ? match[1].trim() : null;
  };

  // 提取 flow_product_id 内容的函数
  const extractFlowProductId = (content: string): string | null => {
    const regex = /<flow_product_id>([\s\S]*?)<\/flow_product_id>/;
    const match = content.match(regex);
    return match ? match[1].trim() : null;
  };

  // 提取 flow_summary_result 内容的函数
  const extractFlowSummaryResult = (content: string): string | null => {
    const regex = /<flow_summary_result>([\s\S]*?)<\/flow_summary_result>/;
    const match = content.match(regex);
    return match ? match[1].trim() : null;
  };

  // 移除 flow_html 标签的函数
  const removeFlowHtmlTags = (content: string): string => {
    const regex = /<flow_html>[\s\S]*?<\/flow_html>/g;
    return content.replace(regex, "");
  };

  // 移除 flow_product_id 标签的函数
  const removeFlowProductIdTags = (content: string): string => {
    const regex = /<flow_product_id>[\s\S]*?<\/flow_product_id>/g;
    return content.replace(regex, "");
  };

  // 移除 flow_summary_result 标签的函数
  const removeFlowSummaryResultTags = (content: string): string => {
    const regex = /<flow_summary_result>[\s\S]*?<\/flow_summary_result>/g;
    return content.replace(regex, "");
  };

  // 移除所有 flow 标签的函数
  const removeAllFlowTags = (content: string): string => {
    let cleanContent = removeFlowHtmlTags(content);
    cleanContent = removeFlowProductIdTags(cleanContent);
    cleanContent = removeFlowSummaryResultTags(cleanContent);
    return cleanContent;
  };

  const flowHtmlContent = extractFlowHtmlContent(display);
  const flowProductId = extractFlowProductId(display);
  const flowSummaryResult = extractFlowSummaryResult(display);
  const cleanContent = removeAllFlowTags(display);

  // 准备总结内容的标签页数据
  const summaryTabs = summaries.map((summary) => ({
    key: summary.id,
    label: `${t('flowRenderer.summary')} ${summaries.indexOf(summary) + 1}`,
    children: (
      <div>
        <div dangerouslySetInnerHTML={{ __html: md.render(summary.think) }} />
        <div style={{ marginTop: 12, textAlign: "right", display: "flex", gap: 8, justifyContent: "flex-end" }}>
          <Button
            type="primary"
            size="small"
            onClick={() => {
              setActiveSummaryId(summary.id);
              if (onSummaryResultClick) {
                onSummaryResultClick((summary.display) || "");
              }
            }}
          >
            {t('flowRenderer.viewSummaryContent')}
          </Button>
          {onSaveMultilang && (
            <Button
              type="primary"
              size="small"
              style={{ backgroundColor: "#52c41a", borderColor: "#52c41a" }}
              onClick={() => {
                onSaveMultilang(
                  summary.display || "",
                  summary.originalChinese || summary.display || "",
                  flowProductId || undefined
                );
              }}
            >
              {t('flowRenderer.saveMultilang')}
            </Button>
          )}
        </div>
      </div>
    ),
  }));

  return (
    <Typography>
      <Collapse
        activeKey={status === "pending" ? ["1"] : undefined}
        items={[
          {
            key: "1",
            label: status === "pending" ? t('flowRenderer.thinking') : t('flowRenderer.thinkingProcess'),
            children: <>
              <div dangerouslySetInnerHTML={{ __html: md.render(think) }} />
            </>
          }
        ]}
      />
      <div dangerouslySetInnerHTML={{ __html: md.render(cleanContent) }} />
      {(flowHtmlContent || flowProductId || summaries.length > 0) && (
        <Card
          size="small"
          style={{ marginTop: 16 }}
          styles={{ body: { padding: 12 } }}
        >
          <Space direction="vertical" style={{ width: "100%" }} size="middle">
            {flowHtmlContent && (
              <Card
                size="small"
                title={t('flowRenderer.detectedFlowHtml')}
                styles={{ body: { padding: 12 } }}
              >
                <Row justify="space-between" align="middle">
                  <Col>
                    <Button
                      type="primary"
                      icon={<EyeOutlined />}
                      onClick={() => onFlowHtmlClick(flowHtmlContent)}
                    >
                      {t('flowRenderer.previewHtml')}
                    </Button>
                  </Col>
                </Row>
              </Card>
            )}

            {flowProductId && onFlowProductIdClick && (
              <Card
                size="small"
                title={`${t('flowRenderer.detectedProductId')}: ${flowProductId}`}
                styles={{ body: { padding: 12 } }}
              >
                <Row justify="space-between" align="middle">
                  <Col>
                    <Button
                      type="primary"
                      icon={<EyeOutlined />}
                      onClick={() => {
                        const callback = () => {
                          onSummaryClick && onSummaryClick(flowProductId, "product", {
                            answerId: answer.id,
                            messageItemId: answer.messageItemId,
                          })
                          setTimeout(() => {
                            setActiveSummaryId(summaryTabs[summaryTabs.length]?.key || null);
                          }, 300);
                        }
                        onFlowProductIdClick(flowProductId, answer.metadata.flightInfo, answer.metadata.flightList
                          ,callback
                        )
                      }}
                    >
                      {t('flowRenderer.viewProductDetail')}
                    </Button>
                  </Col>
                  <Col>
                    {onSummaryClick && (
                      <Button
                        type="default"
                        icon={<FileTextOutlined />}
                        onClick={() =>
                          onSummaryClick(flowProductId, "product", {
                            answerId: answer.id,
                            messageItemId: answer.messageItemId,
                          })
                        }
                      >
                        {t('flowRenderer.summarize')}
                      </Button>
                    )}
                  </Col>
                </Row>
              </Card>
            )}

            {summaries.length > 0 && (
              <Card
                size="small"
                title={`${t('flowRenderer.summaryContent')} (${summaries.length})`}
                styles={{ body: { padding: 12 } }}
              >
                <Tabs
                  items={summaryTabs}
                  activeKey={activeSummaryId|| summaryTabs[summaryTabs.length - 1].key}
                  onChange={(key) => setActiveSummaryId(key)}
                  type="card"
                  tabPosition="left"
                  style={{ maxHeight: 280 }}

                  size="small"
                />
              </Card>
            )}
          </Space>
        </Card>
      )}
    </Typography>
  );
};

export default FlowContentRenderer;